<?php

namespace app\api\logic\xiluhouse;

use app\api\logic\BaseLogic;
use app\common\model\xiluhouse\RentalContact as RentalContactModel;
use app\common\model\xiluhouse\RentalContactView;
use app\common\model\User;
use think\Exception;
use think\Env;

class RentalContactLogic extends BaseLogic
{
    // VIP等级配置
    const MIN_VIP_LEVEL = 1; // 最低VIP等级要求
    
    /**
     * 获取每日免费查看次数限制
     * @return int
     */
    private function getFreeDailyLimit()
    {
        return Env::get('rental.free_daily_limit', 2); // 默认值为2
    }

    /**
     * 检查用户是否是有效VIP
     * @param User $user 用户模型
     * @return bool
     */
    private function isValidVip($user)
    {
        return $user->vip_level >= self::MIN_VIP_LEVEL 
            && $user->vip_expiration_time > time();
    }

    /**
     * 获取用户今日已查看的不同房源数量
     * @param int $user_id 用户ID
     * @return int
     */
    private function getTodayUniqueViewCount($user_id)
    {
        return RentalContactView::where('user_id', $user_id)
            ->where('view_date', date('Y-m-d'))
            ->group('rental_id')
            ->count();
    }

    /**
     * 检查用户今日是否已查看过该房源
     * @param int $user_id 用户ID
     * @param int $rental_id 房源ID
     * @return bool
     */
    private function hasViewedToday($user_id, $rental_id)
    {
        return RentalContactView::where('user_id', $user_id)
            ->where('rental_id', $rental_id)
            ->where('view_date', date('Y-m-d'))
            ->count() > 0;
    }

    /**
     * 查看房源联系方式
     * @param int $rental_id 房源ID
     * @param array $user 用户信息
     * @return array
     */
    public function view($rental_id, $user)
    {
        if (!$rental_id) {
            return ['code' => 0, 'msg' => '房源ID不能为空'];
        }

        try {
            // 获取联系方式信息
            $contact = RentalContactModel::where('rental_id', $rental_id)
                ->where('status', 'normal')
                ->find();
                
            if (!$contact) {
                return ['code' => 0, 'msg' => '联系方式不存在'];
            }

            // 检查用户权限
            $user_model = User::get($user['id']);
            $is_vip = $this->isValidVip($user_model);
            
            // 检查是否已查看过该房源
            $viewed_today = $this->hasViewedToday($user['id'], $rental_id);
            
            if (!$is_vip && !$viewed_today) {
                // 非VIP用户且今日未查看过该房源，检查不同房源的查看次数
                $unique_view_count = $this->getTodayUniqueViewCount($user['id']);
                $free_daily_limit = $this->getFreeDailyLimit();
                
                if ($unique_view_count >= $free_daily_limit) {
                    return ['code' => 0, 'msg' => '今日免费查看不同房源次数已用完，请开通VIP享无限次查看'];
                }
            }

            // 记录查看
            if (!$viewed_today) {
                RentalContactView::recordView($user['id'], $rental_id, $contact->id);
            }

            // 返回联系方式信息
            $contact_info = [
                'wechat_name'   => $contact->wechat_name,
                'mobile'        => $contact->mobile,
                'wechat_num'    => $contact->wechat_num,
                'qq_num'        => $contact->qq_num,
                'contact_time'  => $contact->contact_time
            ];

            // 获取今日剩余次数
            $remain_count = 0;
            if (!$is_vip) {
                $unique_view_count = $this->getTodayUniqueViewCount($user['id']);
                $free_daily_limit = $this->getFreeDailyLimit();
                $remain_count = max(0, $free_daily_limit - $unique_view_count);
            }

            return [
                'code' => 1,
                'msg' => 'success',
                'data' => [
                    'contact' => $contact_info,
                    'is_vip' => $is_vip,
                    'remain_count' => $is_vip ? '无限' : $remain_count,
                    'viewed_today' => $viewed_today,
                    'vip_info' => [
                        'vip_level' => $user_model->vip_level,
                        'vip_expiration_time' => $user_model->vip_expiration_time,
                        'is_expired' => $user_model->vip_expiration_time <= time()
                    ]
                ]
            ];
        } catch (Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 获取查看限制信息
     * @param array $user 用户信息
     * @return array
     */
    public function getLimitInfo($user)
    {
        try {
            $user_model = User::get($user['id']);
            $is_vip = $this->isValidVip($user_model);
            
            $unique_view_count = $this->getTodayUniqueViewCount($user['id']);
            $free_daily_limit = $this->getFreeDailyLimit();
            $remain_count = $is_vip ? '无限' : max(0, $free_daily_limit - $unique_view_count);

            return [
                'code' => 1,
                'msg' => 'success',
                'data' => [
                    'is_vip' => $is_vip,
                    'vip_info' => [
                        'vip_level' => $user_model->vip_level,
                        'vip_expiration_time' => $user_model->vip_expiration_time,
                        'is_expired' => $user_model->vip_expiration_time <= time()
                    ],
                    'today_unique_count' => $unique_view_count, // 今日已查看不同房源数
                    'remain_count' => $remain_count,
                    'daily_limit' => $free_daily_limit,
                    'min_vip_level' => self::MIN_VIP_LEVEL
                ]
            ];
        } catch (Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
} 